{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<__main__.Chain at 0x277bcef0668>"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Chain(object):\n",
    " \n",
    "    def __init__(self, path=''):\n",
    "        self._path = path\n",
    " \n",
    "    def __getattr__(self, path):\n",
    "        return Chain('%s/%s' % (self._path, path))\n",
    " \n",
    "    def __str__(self):\n",
    "        return self._path\n",
    "\n",
    "Chain().a.b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TYPE "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2]"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(list)\n",
    "list\n",
    "list(\"222\")\n",
    "[2]\n",
    "#字典和 【】 是 引用对象 = 是浅拷贝， （)y元组 是固定类型 不会引用 每次都是新的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'no': 1, 'name': '我', 'url': 'http://www.runoob.com', 'arr': [1.1, 2, 3]}\n",
      "Python 原始数据： None\n",
      "JSON 对象： {\"no\": 1, \"name\": \"\\u6211\", \"url\": \"http://www.runoob.com\", \"arr\": [1.1, 2, 3]}\n",
      "data2['name']:  我\n",
      "data2['url']:  http://www.runoob.com\n",
      "\n",
      " {\n",
      "    \"arr\":[\n",
      "        1.1,\n",
      "        2,\n",
      "        3\n",
      "    ],\n",
      "    \"name\":\"我\",\n",
      "    \"no\":1,\n",
      "    \"url\":\"http://www.runoob.com\"\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "import json\n",
    "\n",
    "# Python 字典类型转换为 JSON 对象\n",
    "data1 = {\n",
    "    'no' : 1,\n",
    "    'name' : '我',\n",
    "    'url' : 'http://www.runoob.com',\n",
    "    'arr':[1.1,2,3]\n",
    "}\n",
    "\n",
    "json_str = json.dumps(data1)\n",
    "print (\"Python 原始数据：\", print(data1))\n",
    "print (\"JSON 对象：\", json_str)\n",
    "\n",
    "# 将 JSON 对象转换为 Python 字典\n",
    "data2 = json.loads(json_str)\n",
    "print (\"data2['name']: \", data2['name'])\n",
    "print (\"data2['url']: \", data2['url'])\n",
    "\n",
    "# json 格式化\n",
    "json_str = json.dumps(data1,sort_keys=True, indent=4, separators=(',', ':'),ensure_ascii=False)\n",
    "print(\"\\n\",json_str)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import json\n",
    "\n",
    "json.dump({\"2\":3,\"2\":4})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1.   , 3.   , 5.   , 5.   , 6.124])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pickle\n",
    "\n",
    "with open( \"a.pkl\",\"wb\") as f:\n",
    "    pickle.dump({\"s\":2,\"2\":3},f)\n",
    "    \n",
    "with open( \"a.pkl\",\"rb\") as f:\n",
    "    a=pickle.load(f)\n",
    "a\n",
    "\n",
    "a[\"234\"]=333\n",
    "with open( \"a.pkl\",\"ab\") as f:\n",
    "    pickle.dump(a,f)\n",
    "with open( \"a.pkl\",\"rb\") as f:\n",
    "    a=pickle.load(f)\n",
    "a# 无法追加的 用a 错误的\n",
    "\n",
    "# rw 同时读写\n",
    "\n",
    "with open( \"a.pkl\",\"rb+\") as f:\n",
    "    a=pickle.load(f)  \n",
    "    a[\"aaa\"]=\"+++\"\n",
    "    pickle.dump(1245,f)\n",
    "with open( \"a.pkl\",\"rb\") as f:\n",
    "    b=pickle.load(f)\n",
    "b\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 【【】【】】 to {}\n",
    "list= [['key1','value1'],['key2','value2'],['key3','value3']]\n",
    "tulpe=(('key1','value1'),('key2','value2'),('key3','value3'))\n",
    "dict(tulpe)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "iterable argument unpacking follows keyword argument unpacking (<ipython-input-40-bfec35653368>, line 13)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-40-bfec35653368>\"\u001b[1;36m, line \u001b[1;32m13\u001b[0m\n\u001b[1;33m    dnew= dict(d,**dd,**cc,*{\"sa\":[24,4]})\u001b[0m\n\u001b[1;37m                          ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m iterable argument unpacking follows keyword argument unpacking\n"
     ]
    }
   ],
   "source": [
    "d={\"name\":\"fff\",\"sex\":\"cc\"}\n",
    "# 判断 key 在不在字典里\n",
    "print (\"name\" in d.keys())\n",
    "#转tanlpe\n",
    "print( tuple(d))\n",
    "#update\n",
    "dd={\"sex\":\"dd\",\"id\":12345258};cc={\"mather\":\"fuck\"}\n",
    "dnew=d.copy()\n",
    "dnew.update(dd) #.upate(cc) NOne teyp\n",
    "print(dnew)\n",
    "#-----------\n",
    "dd={\"sex\":\"dd\",\"id\":99999};cc={\"mather\":\"fu\"}\n",
    "dnew= dict(d,**dd,**cc,**{\"sa\":[24,4]}) #更新不能新建\n",
    "print(\"dnew\",dnew)\n",
    "# 转 str\n",
    "print(\"转 str \", str(d))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## dict 2 obj\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class DictToStruct:\n",
    "    def __init__(self, entries):\n",
    "        self.__dict__.update(entries)\n",
    "struct = DictToStruct({\"cc\":2,\"bb\":4})\n",
    "\n",
    "struct.__dict__\n",
    "struct.cc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "32"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class DictObj(object):\n",
    "    def __init__(self,map):\n",
    "        if not isinstance(map,dict):\n",
    "            raise TypeError\n",
    "        self.map = map\n",
    "\n",
    "    def __setattr__(self, name, value):\n",
    "        if name == 'map':\n",
    "             object.__setattr__(self, name, value)\n",
    "             return;\n",
    "        print( 'set attr called ',name,value)\n",
    "        self.map[name] = value\n",
    "\n",
    "    def __getattr__(self,name):\n",
    "        v = self.map[name]\n",
    "        if isinstance(v,(dict)):\n",
    "            return DictObj(v)\n",
    "        if isinstance(v, (list)):\n",
    "            r = []\n",
    "            for i in v:\n",
    "                r.append(DictObj(i))\n",
    "            return r                      \n",
    "        else:\n",
    "            return self.map[name];\n",
    "\n",
    "    def __getitem__(self,name):\n",
    "        return self.map[name]\n",
    "\n",
    "\n",
    "m = {'haha':{'a':55},'bb':[{'c':32,'d':45},{'c':22,'d':56}]}\n",
    "n=[\"2\",\"3\"]\n",
    "book = DictObj(m);\n",
    "book.bb[0].c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fail\n"
     ]
    }
   ],
   "source": [
    "# 内置方法\n",
    "import os \n",
    "#os.environ[\"s\"] \n",
    "print (os.environ.get(\"s\",\"fail\")) # 想比直接取 在失败时返回 默认值 不会异常"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'fff', 'sex': 'cc', 's': 44}\n",
      "{'name': 'fff', 'sex': 'cc', 's': 44}\n",
      "111\n",
      "{'name': 'fff', 'sex': 'cc', 's': {'ss': {'sss': 245}}}\n"
     ]
    }
   ],
   "source": [
    "d={\"name\":\"fff\",\"sex\":\"cc\",\"s\":{ \"ss\":{\"sss\":245} } }\n",
    "\n",
    "dd=d # 字典复制是浅拷贝， 改变所以 子对象\n",
    "dd[\"s\"]=44\n",
    "print(d)\n",
    "for (k,v) in d.items(): # items() 返回的是一个新对象了\n",
    "    v=1\n",
    "print(d)\n",
    "#========\n",
    "d={\"name\":\"fff\",\"sex\":\"cc\",\"s\":{ \"ss\":{\"sss\":245} } }\n",
    "ee=d[\"s\"][\"ss\"]\n",
    "#ee=124\n",
    "ee=111\n",
    "#del ee[\"sss\"]\n",
    "\n",
    "print(ee)# 比较符合直觉的 父对象不会受到子对象的影响 。 ee 是新的地址\n",
    "print(d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# temp"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1536565626"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import time\n",
    "int(time.time())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "UnicodeEncodeError",
     "evalue": "'ascii' codec can't encode character '\\u6211' in position 10: ordinal not in range(128)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mUnicodeEncodeError\u001b[0m                        Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-7-16666b8544c5>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0ms\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m\"245360.101我\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mb\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mencode\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"ascii\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdecode\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mUnicodeEncodeError\u001b[0m: 'ascii' codec can't encode character '\\u6211' in position 10: ordinal not in range(128)"
     ]
    }
   ],
   "source": [
    "s=\"245360.101我\"\n",
    "b=s.encode()\n",
    "print(b)\n",
    "print(b.decode())\n",
    "\n",
    "print( s, type(s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bpa b'\\x80\\x03]q\\x00(K\\x01K-M.\\x12K6e.'\n",
      "spa <class 'str'> Ç\u0003]q\u0000(K\u0001K-M.\u0012K6e.\n",
      "json str  \"\\u00c7\\u0003]q\\u0000(K\\u0001K-M.\\u0012K6e.\"\n",
      "obj <class 'str'> Ç\u0003]q\u0000(K\u0001K-M.\u0012K6e.\n",
      "b'\\x80\\x03]q\\x00(K\\x01K-M.\\x12K6e.'\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[1, 45, 4654, 54]"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# encode\n",
    "s=\"123456\"\n",
    "import pickle,json\n",
    "pa=pickle.dumps([1,45,4654,54]);print(\"bpa\",pa)\n",
    "spa=pa.decode(\"cp437\");print(\"spa\",type(spa),spa)\n",
    "#spa=\"123567\"\n",
    "\n",
    "d=json.dumps(spa) #decode utf-8 s\n",
    "print(\"json str \",d)\n",
    "\n",
    "d=json.loads(d)\n",
    "print(\"obj\",type(d),d)\n",
    "d=d.encode(\"cp437\");print(d)\n",
    "bpa=d\n",
    "pickle.loads(bpa)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "a={\"c\":1}\n",
    "print(a.get(\"s\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 编码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'ë\\x00\\x00'"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import hashlib\n",
    "\n",
    "hashlib.md5(b\"xmadmin@123\").hexdigest()\n",
    "\n",
    "\n",
    "import base64 \n",
    "a=b'\\x89\\x00\\x00'\n",
    "b64=base64.b64encode(a)\n",
    "str(a,\"cp437\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'s': 2, '2': 3}"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
